<template>
    <section>
        <Card style="width:40%;margin-left: 25%;margin-bottom: 6px;">
            <p slot="title">
                <Icon type="ios-person"></Icon>
                个人信息
                <a @click="openPasswordModal" style="float: right;color:#2D8cF0;">修改密码</a>
            </p>
            <i-form :label-width="60">
                <Form-item label="用户名">
                    <Input v-model="form.name" placeholder="请输入用户名" disabled></Input>
                </Form-item>
                <!--<Form-item label="邮箱">-->
                    <!--<Input v-model="form.email" placeholder="请输入邮箱" disabled></Input>-->
                <!--</Form-item>-->
            </i-form>
        </Card>

        <Card style="width:40%;margin-left: 25%;margin-bottom: 6px;">
            <p slot="title">
                <Icon type="ios-flag"></Icon>
                短信通知（机器人掉线、授权到期，发短信通知）
            </p>
            <i-form :label-width="60">
                <Form-item label="手机号">
                    <Input v-model.trim="phone" placeholder="请输入绑定的手机号" :disabled="!!form.phone"></Input>
                </Form-item>
                <Form-item v-if="!form.phone">
                    <Input v-model.trim="captcha" placeholder="验证码" style="width: 36%;"></Input>
                    <Button v-if="!loopTimeInterval" @click="getCode" :loading="codeLoading" type="warning" style="width: 32%;margin-left: 2%;">获取验证码</Button>
                    <Button v-else type="warning" style="width: 32%;margin-left: 2%;">{{time}}s</Button>
                </Form-item>
                <Form-item  v-if="!form.phone">
                    <Button type="primary" style="float: right;" :loading="phoneLoading" @click="bindPhone">绑定</Button>
                </Form-item>
            </i-form>
        </Card>

        <!--重置密码-->
        <Modal v-model="passwordVisible" title="修改密码" :loading="true" :mask-closable="false">
            <Form ref="passwordForm" :model="passwordForm" :label-width="90" :rules="ruleValidate">
                <Form-item label="旧密码" prop="password">
                    <Input type="password" v-model.trim="passwordForm.password" placeholder="请输入旧密码"></Input>
                </Form-item>
                <Form-item label="新密码" prop="passwordNew">
                    <Input type="password" v-model.trim="passwordForm.passwordNew" placeholder="请输入新密码"></Input>
                </Form-item>
                <Form-item label="确认新密码" prop="passwordNewCheck">
                    <Input type="password" v-model.trim="passwordForm.passwordNewCheck" placeholder="请再输入一次新密码"></Input>
                </Form-item>
            </Form>
            <div slot="footer">
                <i-button type="primary" :loading="passwordBtn" @click="updatePassword">更新</i-button>
            </div>
        </Modal>
    </section>
</template>
<script>
    import {localSave} from "@/libs/util";
    import {resetPassword, getUserInfo, setPhone} from '@/api/user';

    export default {
        data() {
            const validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.passwordForm.passwordNew !== '') {
                        // 对第二个密码框单独验证
                        this.$refs.passwordForm.validateField('passwordNewCheck');
                    }
                    callback();
                }
            };
            const validatePassCheck = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.passwordForm.passwordNew) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
            return {
                form: {},
                passwordForm: {},
                passwordVisible: false,//修改密码对话框
                passwordBtn: false,//修改密码对话框
                ruleValidate: {
                    password: [
                        {required: true, message: '密码不能为空', trigger: 'blur'}
                    ],
                    passwordNew: [
                        {required: true, validator: validatePass, trigger: 'blur'}
                    ],
                    passwordNewCheck: [
                        {required: true, validator: validatePassCheck, trigger: 'blur'}
                    ],
                },
                //验证码
                phone:'',
                captcha:'',
                codeLoading: false,
                phoneLoading: false,
                time: 60,
                loopTimeInterval: null,
            }
        },
        methods: {
            //循环倒计时
            loopTime(){
                var self = this;
                this.loopTimeInterval = setInterval(function () {
                    self.time--;
                    if(self.time == 0){
                        clearInterval(self.loopTimeInterval);
                        self.loopTimeInterval = null;
                        self.time = 60;
                    }
                }, 1000)
            },
            //获取验证码
            getCode(){
                if(!this.phone || !(/^1[0-9]{10}$/.test(this.phone))){
                    this.$message.warning('提示：请输入正确的手机号');
                    return;
                }
                this.codeLoading = true;
                captcha({phone: this.phone, register:1, subject: '注册新用户'}).then((res) => {
                    this.codeLoading = false;
                    if(res.code === 0){
                        this.$message.success("提示：验证码已发送");
                        this.loopTime();
                    }else{
                        this.$message.error(res.msg);
                    }
                }).catch(()=>{
                    this.codeLoading = false;
                });
            },
            //获取用户信息
            userInfo(){
                this.form = this.$store.getters.user;
                if(this.form.phone){
                    this.phone = this.form.phone;
                }
                // getUserInfo().then(res=>{
                //     this.form = res;
                //     if(this.form.phone){
                //         this.phone = this.form.phone;
                //     }
                //     localSave(res);
                // });
            },
            openPasswordModal() {
                this.passwordVisible = true;
                this.passwordForm = {};
            },
            updatePassword() {
                this.$refs.passwordForm.validate((valid) => {
                    if (!valid) {
                        this.$Message.error('表单验证失败!');
                        return;
                    } else {
                        if (this.passwordForm.password === '' || !this.passwordForm.passwordNew ||
                            this.passwordForm.passwordNew !== this.passwordForm.passwordNewCheck)
                        {
                            this.$Message.error('表单验证失败!');
                            return;
                        }
                    }
                    let param = {
                        user_id: this.form.id,
                        password_old: this.passwordForm.password,
                        password: this.passwordForm.passwordNew,
                        password_confirmation: this.passwordForm.passwordNewCheck
                    };
                    this.passwordBtn = true;
                    //请求接口修改密码
                    resetPassword(param).then((res) => {
                        this.passwordBtn = false;
                        if(res.code === 0){
                            this.passwordVisible = false;
                            this.$Message.success('提示：修改密码成功');
                        }else{
                            this.$Message.error(res.msg);
                        }
                    });
                });
            },
            //绑定手机
            bindPhone(){
                if(!this.phone || !this.captcha){
                    this.$message.warning("请输入有效的手机号或验证码");
                    return;
                }
                let param = {
                    phone: this.phone,
                    captcha: this.captcha
                };
                this.phoneLoading = true;
                setPhone(param).then((res)=>{
                    this.phoneLoading = false;
                    if(res.code === 0){
                        this.$set(this.form, 'phone', this.phone);
                        this.$message.success("绑定成功");
                    }else{
                        this.$message.error(res.msg);
                    }
                }).catch(()=>{
                    this.phoneLoading = false;
                });
            },
        },
        mounted() {
            this.userInfo();
        }
    }
</script>

<style>
    .var_title{
        padding-bottom:10px;
    }
</style>
